package com.enterprise.support.utility.generator.panel;

import com.enterprise.support.utility.Configuration;
import com.enterprise.support.utility.FileUtility;
import com.enterprise.support.utility.generator.pub.GeneratorConfig;
import com.enterprise.application.swing.jeta.AbstractPanel;
import com.enterprise.support.utility.Enterprise;
import com.enterprise.support.utility.generator.pub.FreemarkerManager;
import com.enterprise.support.utility.SwingUtility;
import org.apache.commons.io.FileUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileFilter;
import java.util.Date;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2011-2-9
 * Time: 11:27:40
 * To change this template use File | Settings | File Templates.
 */
public class TabStruts extends AbstractPanel {
    private final static File srcDirectory = new File(com.enterprise.support.utility.Configuration.LibDirectory, "/java/src");
    private final static File comDirectory = new File(srcDirectory, "com");
    private final static DefaultTableModel tableModel = new DefaultTableModel(new Vector() {{
        add("Action 名字");
    }}, 0);
    private static DefaultComboBoxModel modulesComboBoxModel;

    public TabStruts() {
        super("com\\enterprise\\support\\utility\\generator\\panel\\TabStruts.xml");
    }

    public void initComponents() {
        mainPanel.getComboBox("projects").setModel(new DefaultComboBoxModel(new Vector<Object>() {{
            File[] files = comDirectory.listFiles();
            if (null != files) {
                for (File project : files) {
                    if (project.isDirectory()) {
                        add(project.getName());
                    }
                }
            }
        }}));

        modulesComboBoxModel = new DefaultComboBoxModel(new Vector<Object>() {{
            File moduleDirectory = new File(new File(comDirectory, String.valueOf(mainPanel.getComboBox("projects").getSelectedItem())), "application");
            File[] files = moduleDirectory.listFiles();
            if (null != files) {
                for (File module : files) {
                    if (module.isDirectory()) {
                        add(module.getName());
                    }
                }
            }
        }});

        mainPanel.getComboBox("modules").setModel(modulesComboBoxModel);
        mainPanel.getTable("results").setModel(tableModel);

        File webDirectory = new File(GeneratorConfig.homeDirectory, "/java/src/com/" + mainPanel.getComboBox("projects").getSelectedItem() + "/application/" + mainPanel.getComboBox("modules").getSelectedItem() + "/web/");
        File[] files = webDirectory.listFiles();
        tableModel.getDataVector().clear();
        if (files != null) {
            for (final File file : files) {
                if (file.isFile()) {
                    tableModel.addRow(new Vector() {{
                        add(file.getName());
                    }});
                }
            }
        } else {
            tableModel.addRow(new Vector());
        }
    }

    public void addListeners() {
        mainPanel.getComboBox("projects").addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                modulesComboBoxModel.removeAllElements();
                File moduleDirectory = new File(new File(comDirectory, String.valueOf(mainPanel.getComboBox("projects").getSelectedItem())), "application");
                File[] files = moduleDirectory.listFiles();
                if (files != null) {
                    for (File module : files) {
                        if (module.isDirectory()) {
                            modulesComboBoxModel.addElement(module.getName());
                        }
                    }
                }
            }
        });
        mainPanel.getComboBox("modules").addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == 1) {
                    final File webDirectory = new File(GeneratorConfig.homeDirectory, "/java/src/com/" + mainPanel.getComboBox("projects").getSelectedItem() + "/application/" + mainPanel.getComboBox("modules").getSelectedItem() + "/web/");
                    File[] files = webDirectory.listFiles();
                    tableModel.getDataVector().clear();
                    if (files != null) {
                        for (final File file : files) {
                            if (file.isFile()) {
                                tableModel.addRow(new Vector() {{
                                    add(file.getName());
                                }});
                            }
                        }
                    } else {
                        tableModel.addRow(new Vector());
                    }
                }
            }
        });
        mainPanel.getButton("submit").addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                final Enterprise input = getInput();
                if (input.isEmpty("modules")) {
                    SwingUtility.warning("请选择 模块 ！");
                } else if (input.isEmpty("classname")) {
                    SwingUtility.warning("请输入 Action 名称！");
                } else if (input.getString("classname").toLowerCase().indexOf("action") != -1) {
                    SwingUtility.warning("请去除 Action 名称中的 Action 关键字！");
                } else {


                    input.set("date", new Date());
                    input.set("classname", input.getString("classname").trim().toLowerCase());
                    input.set("actionName", input.getString("classname").replaceFirst("[a-z]", input.getString("classname").substring(0, 1).toUpperCase()) + "Action");

                    File webDirectory = new File(GeneratorConfig.homeDirectory, "/java/src/com/" + input.getString("projects") + "/application/" + input.getString("modules") + "/web/");
                    String action = new File(webDirectory, input.getString("actionName") + ".java").getAbsolutePath();

                    for (Object values : tableModel.getDataVector()) {
                        if (input.equals("actionName", String.valueOf(((Vector) values).get(0)).replace(".java", ""))) {
                            if (SwingUtility.confirm(String.valueOf(((Vector) values).get(0)).replace(".java", "") + " 已存在,是否需要覆盖！") != JOptionPane.YES_OPTION) {
                                return;
                            }
                        }
                    }

                    FreemarkerManager.builerTemplate("Action.ftl", input, action);
                    SwingUtility.warning("Action 对象已生成！");

                    for (Object values : tableModel.getDataVector()) {
                        if (input.equals("actionName", String.valueOf(((Vector) values).get(0)).replace(".java", ""))) {
                            return;
                        }
                    }
                    tableModel.addRow(new Vector() {{
                        add(input.getString("actionName") + ".java");
                    }});
                }
            }
        });
        mainPanel.getButton("deploy").addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                File[] files = GeneratorConfig.homeDirectory.listFiles(new FileFilter() {
                    public boolean accept(File file) {
                        if (null != file.listFiles())
                            for (File child : file.listFiles())
                                if (child.isDirectory() && "WEB-INF".equalsIgnoreCase(child.getName()))
                                    return true;
                        return false;
                    }
                });
                if (files == null || files.length < 1) {
                    SwingUtility.warning("Sorry！你当前的工程非 Web 项目，不能执该操作！");
                    return;
                }
                File webInfo = new File(files[0], "/WEB-INF/web.xml");
                if (webInfo.exists() && SwingUtility.confirm("web.xml文件以存在,确定覆盖？") != JOptionPane.YES_OPTION) {
                    return;
                }

                try {
                    FileUtility.writeFile(webInfo, Configuration.class.getResourceAsStream("/config/web/web.xml"));
                    SwingUtility.info("Ok,部署完成！");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
